package com.ZeroCarbon.config;

import feign.Feign;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.ErrorDecoder;
import feign.jackson.JacksonDecoder;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign配置类
 */
@Configuration
public class FeignConfig {

    @Bean("requestInterceptor")
    public static RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest();
                    String userId = request.getHeader("userId");
                    //将userId保存到，不重置该信息
                    requestTemplate.header("userId", userId);
                }
            }
        };
    }

    public static <T> T createClient(Class<T> clientInterface, String url) {
        return Feign.builder()
                .contract(new SpringMvcContract())  //配置Feign 使用 Spring MVC 的注解解析规则
                .decoder(new JacksonDecoder())  //用于解码响应
                .errorDecoder(new ErrorDecoder.Default())  //错误解码器
                .logLevel(Logger.Level.FULL)  //日志级别
                .requestInterceptor(requestTemplate -> {
                    // 添加请求头
                    requestTemplate.header("Content-Type", "application/json");
                })
                .target(clientInterface, url);  //创建Feign客户端
    }
}
